import numpy as np

def piecewise_linear_interpolation(x_points, y_points, x_experiment):
    # return np.interp(x_experiment, x_points, y_points)
    """
    分段线性插值法。

    参数：
    - x_points : List[float]
        已知数据点的x坐标。
    - y_points : List[float]
        已知数据点的y坐标。
    - x_experiment : List[float]
        需要进行插值估算的x坐标列表。

    返回：
    - List[float]
        x_experiment处的插值值。
    """

    # 结果数组
    y_experiment = np.zeros_like(x_experiment, dtype=float)

    for i, x in enumerate(x_experiment):
        # 找到 x 的插值区间
        if x < x_points[0]:
            y_experiment[i] = y_points[0]
        elif x >= x_points[-1]:
            y_experiment[i] = y_points[-1]
        else:
            # 遍历样本点寻找插值区间
            for j in range(len(x_points)):
                if x >= x_points[j] and x <= x_points[j + 1]:
                    # 计算斜率
                    k = (y_points[j + 1] - y_points[j]) / (x_points[j + 1] - x_points[j])
                    y_experiment[i] = k * (x - x_points[j]) + y_points[j]   
                    break
    return y_experiment